package com.letv.android.client.album.controller;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.inputmethod.InputMethodManager;
import com.ledim.datastatistics.LeDimAnalysisUtils;
import com.letv.ads.ADPlayFragment;
import com.letv.ads.AdsManager;
import com.letv.android.client.LetvSDK;
import com.letv.android.client.activity.AlbumPlayActivity;
import com.letv.android.client.activity.AlbumPlayRoomActivity;
import com.letv.android.client.controller.AlbumGestureObservable;
import com.letv.android.client.fragment.AlbumHalfControllerFragment;
import com.letv.android.client.fragment.AlbumPlayFragment;
import com.letv.android.client.fragment.AlbumRoomPlayFragment;
import com.letv.android.client.listener.OrientationSensorListener;
import com.letv.android.client.utils.ChangeOrientationHandler;
import com.letv.business.flow.album.AlbumPlayFlow;
import com.letv.business.flow.album.listener.PlayAdFragmentListener;
import com.letv.core.bean.VideoBean;
import com.letv.core.config.LetvConfig;
import com.letv.core.constant.PlayConstant;
import com.letv.core.db.PreferencesManager;
import com.letv.core.utils.ActivityUtils;
import com.letv.core.utils.LetvUtils;
import com.letv.core.utils.LogInfo;
import com.letv.core.utils.StatisticsUtils;
import com.letv.core.utils.StringUtils;
import com.letv.core.utils.UIsUtils;
import com.letv.datastatistics.DataStatistics;
import com.letv.datastatistics.util.PageIdConstant;
import com.letv.tracker2.agnes.VideoPlay;

/**
 * 点播控制器
 *
 * @author zhuqiao
 */
public class AlbumController {

    private AlbumPlayActivity mActivity;
    private AlbumPlayRoomActivity mRoomActivity;

    // 转屏Listener
    private OrientationSensorListener mOrientationSensorListener;
    private SensorManager mSensorManager;

    // 全景陀螺仪，重力感应
    private SensorEventListener mPanoramaSensorListener, mPanoramaSensorListenerG;

    public AlbumController(Activity activity) {
        if (activity.getClass() == AlbumPlayActivity.class) {
            mActivity = (AlbumPlayActivity) activity;
        } else {
            mRoomActivity = (AlbumPlayRoomActivity) activity;
        }
    }

    /**
     * 初始化默认陀螺仪
     */
    public void initDefaultSensor() {
        if (mActivity == null) {
            Handler orientationHandler = new ChangeOrientationHandler(mRoomActivity);
            mSensorManager = (SensorManager) mRoomActivity.getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            mOrientationSensorListener =
                    new OrientationSensorListener(orientationHandler, mRoomActivity);
            mSensorManager.registerListener(mOrientationSensorListener, sensor, SensorManager.SENSOR_DELAY_GAME);
        } else {
            Handler orientationHandler = new ChangeOrientationHandler(mActivity);
            mSensorManager = (SensorManager) mActivity.getSystemService(Context.SENSOR_SERVICE);
            Sensor sensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
            mOrientationSensorListener =
                    new OrientationSensorListener(orientationHandler, mActivity);

            mSensorManager.registerListener(mOrientationSensorListener, sensor, SensorManager.SENSOR_DELAY_GAME);
        }
    }

    /**
     * 初始化全景陀螺仪
     */
    private void initPanoramaSensor() {
        // mSensorManager = (SensorManager) mActivity.getSystemService(Context.SENSOR_SERVICE);
        // Sensor orientationSensorG = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
        // mPanoramaSensorListener = new SensorEventListener() {
        //
        // @Override
        // public void onSensorChanged(SensorEvent event) {
        // float axisX = event.values[0];// (Math.PI*2))*360;
        // float axisY = event.values[1];// (Math.PI*2))*360;
        // float axisZ = event.values[2];// (Math.PI*2))*360;
        //
        // if (mActivity.getAlbumPlayFragment() != null && mActivity.getAlbumPlayFragment().getVideoView() != null) {
        // try {
        // mActivity.getAlbumPlayFragment().getVideoView().setgravity_yroInfomation(axisX, axisY, axisZ);
        // } catch (Exception e) {
        // }
        // }
        // }
        //
        // @Override
        // public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //
        // }
        //
        // };
        // mPanoramaSensorListenerG = new SensorEventListener() {
        //
        // @Override
        // public void onSensorChanged(SensorEvent event) {
        // float gx = event.values[0];
        // float gy = event.values[1];
        // float gz = event.values[2];
        //
        // if (event.sensor.getType() == Sensor.TYPE_GRAVITY) {
        // if (mActivity.getAlbumPlayFragment() != null
        // && mActivity.getAlbumPlayFragment().getVideoView() != null) {
        // try {
        // mActivity.getAlbumPlayFragment().getVideoView().setGravityInfomation(gx, gy, gz);
        // } catch (Exception e) {
        // }
        // }
        // }
        //
        // int orientation = -1;
        // float magnitude = gx * gx + gy * gy;
        // // Don't trust the angle if the magnitude is small compared to the y
        // // value
        // if (magnitude * 4 >= gz * gz) {
        // float OneEightyOverPi = 57.29577957855f;
        // float angle = (float) Math.atan2(-gy, gx) * OneEightyOverPi;
        // orientation = 90 - (int) Math.round(angle);
        // // normalize to 0 - 359 range
        // while (orientation >= 360) {
        // orientation -= 360;
        // }
        // while (orientation < 0) {
        // orientation += 360;
        // }
        // }
        //
        // if (orientation >= 60 && orientation <= 120) {
        // LogInfo.log("zhuqiao", "正横屏");
        // } else if (orientation > 150 && orientation < 210) {
        // LogInfo.log("zhuqiao", "正竖屏");
        // } else if (orientation > 240 && orientation < 300) {
        // LogInfo.log("zhuqiao", "反横屏");
        // } else if ((orientation > 330 && orientation < 360)) {
        // LogInfo.log("zhuqiao", "反竖屏");
        // }
        // }
        //
        // @Override
        // public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // }
        // };
        // mSensorManager.registerListener(mPanoramaSensorListener,
        // mSensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE), SensorManager.SENSOR_DELAY_GAME);
        // mSensorManager.registerListener(mPanoramaSensorListenerG, orientationSensorG,
        // SensorManager.SENSOR_DELAY_GAME);
    }

    public boolean fullBack() {
        if (mActivity == null) {
            if (mRoomActivity.mLaunchMode == PlayConstant.LAUNCH_MODE_VIDEO ||
                    mRoomActivity.mIs4dVideo ||
                    mRoomActivity.mLaunchMode == PlayConstant.LAUNCH_MODE_URI) {
                mRoomActivity.getController().back();
                return true;
            }
        } else {
            if (mActivity.mLaunchMode == PlayConstant.LAUNCH_MODE_VIDEO || mActivity.mIs4dVideo ||
                    mActivity.mLaunchMode == PlayConstant.LAUNCH_MODE_URI) {
                mActivity.getController().back();
                return true;
            }
        }

        return false;
    }

    /**
     * 返回
     */
    public void back() {
        AlbumPlayFlow flow;
        if (mActivity == null) {
            // back將输入法隐藏 by zhanghongfei 2015/1/18.
            InputMethodManager manager =
                    (InputMethodManager) mRoomActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (mRoomActivity.getCurrentFocus() != null &&
                    mRoomActivity.getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(mRoomActivity.getCurrentFocus()
                                                             .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }

            mRoomActivity.finish();

            if (mRoomActivity.getFlow() == null) {
                return;
            }

            flow = mRoomActivity.getFlow();

            // zhudeshuai:添加三方调起返回逻辑
            if (flow.getFrom() == PlayConstant.LAUNCH_FROM_MSITE) {
                LogInfo.log("zhuqiao", "back:" + flow.isBackToOriginalApp());
                if (flow.isBackToOriginalApp()) {
                    ActivityUtils.getInstance().removeAll();
                } else {
                    String scheme = "video://video";
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.putExtra("from_M", true);
                    intent.setData(Uri.parse(scheme));
                    mRoomActivity.startActivity(intent);
                    mRoomActivity.finish();
                }

                return;
            }

            String userClickBackTime = "";
            long userClickBackStartTime = 0l;
            if (mRoomActivity.getFullControllerFragment() != null) {
                userClickBackTime =
                        mRoomActivity.getFullControllerFragment().getUserClickBackTime();
                userClickBackStartTime =
                        mRoomActivity.getFullControllerFragment().getUserClickBackStartTime();
            }
            if (TextUtils.isEmpty(userClickBackTime) &&
                    mRoomActivity.getHalfControllerFragment() != null) {
                userClickBackTime =
                        mRoomActivity.getHalfControllerFragment().getUserClickBackTime();
                userClickBackStartTime =
                        mRoomActivity.getHalfControllerFragment().getUserClickBackStartTime();
            }
            if (TextUtils.isEmpty(userClickBackTime)) {
                userClickBackTime = StringUtils.timeClockString("yyyyMMdd_HH:mm:ss");
                userClickBackStartTime = System.currentTimeMillis();
            }
            StringBuilder sb = new StringBuilder();
            sb.append("time=").append(userClickBackTime).append("&");
            if (StringUtils.staticticsLoadTimeInfoFormat(
                    System.currentTimeMillis() - userClickBackStartTime) == 0.0) {
                sb.append("ut=").append("-").append("&");
            } else {
                sb.append("ut=")
                  .append(StringUtils.staticticsLoadTimeInfoFormat(
                          System.currentTimeMillis() - userClickBackStartTime))
                  .append("&");
            }
            if (flow.getLaunchMode() == PlayConstant.PLAY_DOWNLOAD ||
                    flow.getLaunchMode() == PlayConstant.PLAY_DEFAULT) {
                sb.append("pageid=").append(PageIdConstant.fullPlayPage);
            } else {
                sb.append("pageid=").append(PageIdConstant.halpPlayPage);
            }
            String cid = "";
            try {
                cid = (flow.getPlayingVideo() != null) ? String.valueOf(flow.getPlayingVideo()
                                                                            .getCid()) : "-";
                // 统计
                DataStatistics.getInstance()
                              .sendActionInfo(mRoomActivity, "0", "0", LetvConfig.getPcode(mActivity), "29", sb
                                              .toString(), "0",
                                      cid + "", null, flow.getVid() +
                                              "", LetvUtils.getUID(), null, null, null, null,
                                      PreferencesManager.getInstance(mRoomActivity).isLogin() ? 0
                                                                                              : 1, null);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //            finishPlayer();

            /**
             * 5.6需求：点播在按返回键的时候增加页面的曝光上报
             */
            try {
                // 直播中的回看播放源
                // 推送过来的视频直接
                String pageId = StatisticsUtils.getPageId();
                String fl = StatisticsUtils.getFl();
                if (!TextUtils.isEmpty(pageId) && !pageId.equals("053") &&
                        flow.getFrom() == PlayConstant.LAUNCH_FROM_VCR) {
                    StatisticsUtils.staticticsInfoPost(mRoomActivity, "19", fl, null, -1, null, pageId, cid, null,
                            flow.getVid() + "", null, null);
                    LogInfo.LogStatistics(
                            "点播-->回看：fl=" + fl + " ,pageid=" + pageId + " ,cid=" + cid);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            // back將输入法隐藏 by zhanghongfei 2015/1/18.
            InputMethodManager manager =
                    (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            if (mActivity.getCurrentFocus() != null &&
                    mActivity.getCurrentFocus().getWindowToken() != null) {
                manager.hideSoftInputFromWindow(mActivity.getCurrentFocus()
                                                         .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }

            mActivity.finish();

            if (mActivity.getFlow() == null) {
                return;
            }

            flow = mActivity.getFlow();

            // zhudeshuai:添加三方调起返回逻辑
            if (flow.getFrom() == PlayConstant.LAUNCH_FROM_MSITE) {
                LogInfo.log("zhuqiao", "back:" + flow.isBackToOriginalApp());
                if (flow.isBackToOriginalApp()) {
                    ActivityUtils.getInstance().removeAll();
                } else {
                    String scheme = "video://video";
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.putExtra("from_M", true);
                    intent.setData(Uri.parse(scheme));
                    mActivity.startActivity(intent);
                    mActivity.finish();
                }

                return;
            }

            String userClickBackTime = "";
            long userClickBackStartTime = 0l;
            if (mActivity.getFullControllerFragment() != null) {
                userClickBackTime = mActivity.getFullControllerFragment().getUserClickBackTime();
                userClickBackStartTime =
                        mActivity.getFullControllerFragment().getUserClickBackStartTime();
            }
            if (TextUtils.isEmpty(userClickBackTime) &&
                    mActivity.getHalfControllerFragment() != null) {
                userClickBackTime = mActivity.getHalfControllerFragment().getUserClickBackTime();
                userClickBackStartTime =
                        mActivity.getHalfControllerFragment().getUserClickBackStartTime();
            }
            if (TextUtils.isEmpty(userClickBackTime)) {
                userClickBackTime = StringUtils.timeClockString("yyyyMMdd_HH:mm:ss");
                userClickBackStartTime = System.currentTimeMillis();
            }
            StringBuilder sb = new StringBuilder();
            sb.append("time=").append(userClickBackTime).append("&");
            if (StringUtils.staticticsLoadTimeInfoFormat(
                    System.currentTimeMillis() - userClickBackStartTime) == 0.0) {
                sb.append("ut=").append("-").append("&");
            } else {
                sb.append("ut=")
                  .append(StringUtils.staticticsLoadTimeInfoFormat(
                          System.currentTimeMillis() - userClickBackStartTime))
                  .append("&");
            }
            if (flow.getLaunchMode() == PlayConstant.PLAY_DOWNLOAD ||
                    flow.getLaunchMode() == PlayConstant.PLAY_DEFAULT) {
                sb.append("pageid=").append(PageIdConstant.fullPlayPage);
            } else {
                sb.append("pageid=").append(PageIdConstant.halpPlayPage);
            }
            String cid = "";
            try {
                cid = (flow.getPlayingVideo() != null) ? String.valueOf(flow.getPlayingVideo()
                                                                            .getCid()) : "-";
                // 统计
                DataStatistics.getInstance()
                              .sendActionInfo(mActivity, "0", "0", LetvConfig.getPcode(mActivity), "29", sb
                                              .toString(), "0",
                                      cid + "", null, flow.getVid() +
                                              "", LetvUtils.getUID(), null, null, null, null,
                                      PreferencesManager.getInstance(mActivity).isLogin() ? 0
                                                                                          : 1, null);
            } catch (Exception e) {
                e.printStackTrace();
            }

            //            finishPlayer();
            /**
             * 5.6需求：点播在按返回键的时候增加页面的曝光上报
             */
            try {
                // 直播中的回看播放源
                // 推送过来的视频直接
                String pageId = StatisticsUtils.getPageId();
                String fl = StatisticsUtils.getFl();
                if (!TextUtils.isEmpty(pageId) && !pageId.equals("053") &&
                        flow.getFrom() == PlayConstant.LAUNCH_FROM_VCR) {
                    StatisticsUtils.staticticsInfoPost(mActivity, "19", fl, null, -1, null, pageId, cid, null,
                            flow.getVid() + "", null, null);
                    LogInfo.LogStatistics(
                            "点播-->回看：fl=" + fl + " ,pageid=" + pageId + " ,cid=" + cid);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 切到全屏
     */
    public void full() {
        if (mActivity == null) {
            lockOnce(mRoomActivity.getRequestedOrientation());
            UIsUtils.setScreenLandscape(mRoomActivity);
            refreshLandspaceWhenLock();
        } else {
            lockOnce(mActivity.getRequestedOrientation());
            UIsUtils.setScreenLandscape(mActivity);
            refreshLandspaceWhenLock();
        }

    }

    /**
     * 全屏并且锁定
     */
    public void fullLock() {
        setLock(true);
        if (mActivity == null) {
            UIsUtils.setScreenLandscape(mRoomActivity);
        } else {
            UIsUtils.setScreenLandscape(mActivity);
        }

    }

    /**
     * 切到半屏
     */
    public void half() {
        if (mActivity == null) {
            lockOnce(mRoomActivity.getRequestedOrientation());
            UIsUtils.setScreenPortrait(mRoomActivity);

            // 统计
            String userClickBackTime = "";
            long userClickBackStartTime = 0l;
            if (mRoomActivity.getFullControllerFragment() != null) {
                userClickBackTime =
                        mRoomActivity.getFullControllerFragment().getUserClickBackTime();
                userClickBackStartTime =
                        mRoomActivity.getFullControllerFragment().getUserClickBackStartTime();
            }

            if (TextUtils.isEmpty(userClickBackTime)) {
                userClickBackTime = StringUtils.timeClockString("yyyyMMdd_HH:mm:ss");
                userClickBackStartTime = System.currentTimeMillis();
            }
            StringBuilder sb = new StringBuilder();
            if (userClickBackTime == null) {
                sb.append("time=").append("-").append("&");
            } else {
                sb.append("time=").append(userClickBackTime).append("&");
            }
            if (StringUtils.staticticsLoadTimeInfoFormat(
                    System.currentTimeMillis() - userClickBackStartTime) == 0.0) {
                sb.append("ut=").append("-").append("&");
            } else {
                sb.append("ut=")
                  .append(StringUtils.staticticsLoadTimeInfoFormat(
                          System.currentTimeMillis() - userClickBackStartTime))
                  .append("&");
            }
            sb.append("pageid=").append(PageIdConstant.fullPlayPage);

            String cid = "";
            String vid = "";
            if (mRoomActivity.getFlow() == null ||
                    mRoomActivity.getFlow().getPlayingVideo() == null) {
                cid = "-";
                vid = "-";
                LogInfo.LogStatistics("cid or vid is null!");
            } else {
                cid = mRoomActivity.getFlow().getPlayingVideo().getCid() + "";
                vid = mRoomActivity.getFlow().getPlayingVideo().getVid() + "";
            }
            DataStatistics.getInstance()
                          .sendActionInfo(mRoomActivity, "0", "0", LetvConfig.getPcode(mActivity), "29", sb
                                          .toString(), "0", cid, null, vid, LetvUtils
                                          .getUID(), null, null, null, null,
                                  PreferencesManager.getInstance(mRoomActivity).isLogin() ? 0
                                                                                          : 1, null);
        } else {
            lockOnce(mActivity.getRequestedOrientation());
            UIsUtils.setScreenPortrait(mActivity);

            // 统计
            String userClickBackTime = "";
            long userClickBackStartTime = 0l;
            if (mActivity.getFullControllerFragment() != null) {
                userClickBackTime = mActivity.getFullControllerFragment().getUserClickBackTime();
                userClickBackStartTime =
                        mActivity.getFullControllerFragment().getUserClickBackStartTime();
            }

            if (TextUtils.isEmpty(userClickBackTime)) {
                userClickBackTime = StringUtils.timeClockString("yyyyMMdd_HH:mm:ss");
                userClickBackStartTime = System.currentTimeMillis();
            }
            StringBuilder sb = new StringBuilder();
            if (userClickBackTime == null) {
                sb.append("time=").append("-").append("&");
            } else {
                sb.append("time=").append(userClickBackTime).append("&");
            }
            if (StringUtils.staticticsLoadTimeInfoFormat(
                    System.currentTimeMillis() - userClickBackStartTime) == 0.0) {
                sb.append("ut=").append("-").append("&");
            } else {
                sb.append("ut=")
                  .append(StringUtils.staticticsLoadTimeInfoFormat(
                          System.currentTimeMillis() - userClickBackStartTime))
                  .append("&");
            }
            sb.append("pageid=").append(PageIdConstant.fullPlayPage);

            String cid = "";
            String vid = "";
            if (mActivity.getFlow() == null || mActivity.getFlow().getPlayingVideo() == null) {
                cid = "-";
                vid = "-";
                LogInfo.LogStatistics("cid or vid is null!");
            } else {
                cid = mActivity.getFlow().getPlayingVideo().getCid() + "";
                vid = mActivity.getFlow().getPlayingVideo().getVid() + "";
            }
            DataStatistics.getInstance()
                          .sendActionInfo(mActivity, "0", "0", LetvConfig.getPcode(mActivity), "29", sb
                                          .toString(), "0", cid, null, vid, LetvUtils
                                          .getUID(), null, null, null, null,
                                  PreferencesManager.getInstance(mActivity).isLogin() ? 0
                                                                                      : 1, null);
        }

    }

    /**
     * 暂停
     */
    public void pause(boolean showPauseVideo) {
        if (mActivity == null) {
            if (mRoomActivity.getFlow() == null || mRoomActivity.getAlbumPlayFragment() == null) {
                return;
            }

            AlbumPlayFlow flow = mRoomActivity.getFlow();
            AlbumRoomPlayFragment playFragment = mRoomActivity.getAlbumPlayFragment();

            playFragment.pause();

            if (flow.getPlayingVideo() == null || !showPauseVideo ||
                    playFragment.mIsSeekByUser) {// 点进度条的位置快进快退的时候不显示暂停广告
                return;
            }

            VideoBean video = flow.getPlayingVideo();

            if (!flow.isDownloadFile() && !video.needPay() &&
                    !AlbumPlayRoomActivity.sIsShowingLongwatch &&
                    !AlbumPlayRoomActivity.sIsBlockPause &&
                    mRoomActivity.getPlayAdListener() != null) {
                // 得到暂停广告
                AdsManager.getInstance().setFromPush(LetvSDK.getInstance().isPush());
                mRoomActivity.getPlayAdListener()
                             .getDemandPauseAd(video.getCid(), flow.getAid(), flow.getVid(), video.getMid(), flow
                                             .getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mRoomActivity)
                                                                                         .getUserId(),
                                     video.getDuration() + "", "", "0");
            }
            if (video.needPay()) {
                //                if (flow instanceof AlbumPlayTopicFlow) {
                //                    AdsManager.getInstance().setFromPush(LetvApplication.getInstance().isPush());
                //                    AdsManager.getInstance().setFromPush(LetvSDK.getInstance().isPush());
                //                }
                AdsManager.getInstance()
                          .getFrontVipAd(mRoomActivity, video.getCid(), flow.getAid(), flow.getVid(), video
                                          .getMid(), flow.getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mRoomActivity)
                                                                                                     .getUserId(),
                                  video.getDuration() +
                                          "", "", "0", video.needPay(), true, "6");// 上报广告动作
            }
        } else {
            if (mActivity.getFlow() == null || mActivity.getAlbumPlayFragment() == null) {
                return;
            }

            AlbumPlayFlow flow = mActivity.getFlow();
            AlbumPlayFragment playFragment = mActivity.getAlbumPlayFragment();

            playFragment.pause();

            if (flow.getPlayingVideo() == null || !showPauseVideo ||
                    playFragment.mIsSeekByUser) {// 点进度条的位置快进快退的时候不显示暂停广告
                return;
            }

            VideoBean video = flow.getPlayingVideo();

            if (!flow.isDownloadFile() && !video.needPay() &&
                    !AlbumPlayActivity.sIsShowingLongwatch && !AlbumPlayActivity.sIsBlockPause &&
                    mActivity.getPlayAdListener() != null) {
                // 得到暂停广告
                AdsManager.getInstance().setFromPush(LetvSDK.getInstance().isPush());
                mActivity.getPlayAdListener()
                         .getDemandPauseAd(video.getCid(), flow.getAid(), flow.getVid(), video.getMid(), flow
                                         .getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mActivity)
                                                                                     .getUserId(),
                                 video.getDuration() + "", "", "0");
            }
            if (video.needPay()) {
                //                if (flow instanceof AlbumPlayTopicFlow) {
                //                    AdsManager.getInstance().setFromPush(LetvApplication.getInstance().isPush());
                //                    AdsManager.getInstance().setFromPush(LetvSDK.getInstance().isPush());
                //                }
                AdsManager.getInstance()
                          .getFrontVipAd(mActivity, video.getCid(), flow.getAid(), flow.getVid(), video
                                          .getMid(), flow.getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mActivity)
                                                                                                     .getUserId(),
                                  video.getDuration() +
                                          "", "", "0", video.needPay(), true, "6");// 上报广告动作
            }
        }

    }

    /**
     * 开始
     */
    public void start() {
        if (mActivity == null) {
            if (mRoomActivity.getFlow() == null || mRoomActivity.getPlayAdListener() == null ||
                    mRoomActivity.getAlbumPlayFragment() == null) {
                return;
            }

            AlbumPlayFlow flow = mRoomActivity.getFlow();
            PlayAdFragmentListener adListener = mRoomActivity.getPlayAdListener();
            AlbumRoomPlayFragment playFragment = mRoomActivity.getAlbumPlayFragment();

            playFragment.setEnforcementPause(false);
            flow.setIsPauseAdIsShow(false);

            if (flow.isDownloadFile() && playFragment.getPlayingHandler() != null &&
                    mRoomActivity.getFlow().getPlayInfo().currTime != 0) {
                playFragment.start();
            } else if (adListener instanceof AlbumPlayAdController &&
                    ((AlbumPlayAdController) adListener).getAdFragment() != null) {
                ADPlayFragment adFragment = ((AlbumPlayAdController) adListener).getAdFragment();
                adFragment.closePauseAd();

                if (adFragment.isPauseAd()) {
                    if (flow.isAlreadyPlayAd()) {
                        return;
                    }

                    adListener.setADPause(false);
                    adListener.setPauseAd(false);
                    flow.getPlayInfo().mAdConsumeTime = System.currentTimeMillis();
                    // flow.getPlayInfo().mAdsPlayFirstFrameTime = adFragment.getAdsPlayFirstFrameTime();
                    // flow.getPlayInfo().mAdsInteractiveTimeInFact = adFragment.getAdsInteractiveTimeInFact();
                    if (flow.getPlayingVideo() != null) {
                        VideoBean video = flow.getPlayingVideo();
                        adListener.getDemandFrontAd(video.getCid(), flow.getAid(), flow.getVid(), video
                                        .getMid(), flow.getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mRoomActivity)
                                                                                                   .getUserId(),
                                video.getDuration() + "", "", "0", LetvSDK
                                                                          .getPinjie(), video.needPay(), false, true, flow
                                        .isWo3GUser(), PreferencesManager.getInstance(mRoomActivity)
                                                                         .getUtp());
                    }
                } else {
                    if (!adListener.isPlaying()) {
                        if (playFragment.getVideoView() == null ||
                                !playFragment.getVideoView().isPaused()) {
                            if (mRoomActivity.getLoadListener() != null) {
                                mRoomActivity.getLoadListener().loadingVideo(null);
                            }
                        }
                        playFragment.setEnforcementWait(false);
                    }

                    adListener.setPauseAd(false);
                    playFragment.start();
                    // }
                }
            }
        } else {
            if (mActivity.getFlow() == null || mActivity.getPlayAdListener() == null ||
                    mActivity.getAlbumPlayFragment() == null) {
                return;
            }

            AlbumPlayFlow flow = mActivity.getFlow();
            PlayAdFragmentListener adListener = mActivity.getPlayAdListener();
            AlbumPlayFragment playFragment = mActivity.getAlbumPlayFragment();

            playFragment.setEnforcementPause(false);
            flow.setIsPauseAdIsShow(false);

            if (flow.isDownloadFile() && playFragment.getPlayingHandler() != null &&
                    mActivity.getFlow().getPlayInfo().currTime != 0) {
                playFragment.start();
            } else if (adListener instanceof AlbumPlayAdController &&
                    ((AlbumPlayAdController) adListener).getAdFragment() != null) {
                ADPlayFragment adFragment = ((AlbumPlayAdController) adListener).getAdFragment();
                adFragment.closePauseAd();

                if (adFragment.isPauseAd()) {
                    if (flow.isAlreadyPlayAd()) {
                        return;
                    }

                    adListener.setADPause(false);
                    adListener.setPauseAd(false);
                    flow.getPlayInfo().mAdConsumeTime = System.currentTimeMillis();
                    // flow.getPlayInfo().mAdsPlayFirstFrameTime = adFragment.getAdsPlayFirstFrameTime();
                    // flow.getPlayInfo().mAdsInteractiveTimeInFact = adFragment.getAdsInteractiveTimeInFact();
                    if (flow.getPlayingVideo() != null) {
                        VideoBean video = flow.getPlayingVideo();
                        adListener.getDemandFrontAd(video.getCid(), flow.getAid(), flow.getVid(), video
                                        .getMid(), flow.getPlayInfo().mUuidTimp, PreferencesManager.getInstance(mActivity)
                                                                                                   .getUserId(),
                                video.getDuration() + "", "", "0", LetvSDK
                                                                          .getPinjie(), video.needPay(), false, true, flow
                                        .isWo3GUser(), PreferencesManager.getInstance(mActivity)
                                                                         .getUtp());
                    }
                } else {
                    if (!adListener.isPlaying()) {
                        if (playFragment.getVideoView() == null ||
                                !playFragment.getVideoView().isPaused()) {
                            if (mActivity.getLoadListener() != null) {
                                mActivity.getLoadListener().loadingVideo(null);
                            }
                        }
                        playFragment.setEnforcementWait(false);
                    }

                    adListener.setPauseAd(false);
                    playFragment.start();
                    // }
                }
            }
        }

    }

    public void finishPlayer() {
        finishPlayer(false);
    }

    public void finishPlayer(boolean isJumpToPip) {
        // if (MainActivityGroup.getInstance() != null) {
        // if (MainActivityGroup.getInstance().isFromBaiduAndLesoAndWandoujia()) {
        // MainActivityGroup.getInstance().finish();
        // }
        // MainActivityGroup.getInstance().setThirdPartName(null);
        // }
        //

        // 判断是否是跳直播
        //        if (!LiveLaunchUtils.checkJumpLive(mActivity, isJumpToPip)) {
        //            mActivity.finish();
        //            LetvApplication.getInstance().setPlayerFavouriteClick(true);
        //        }

        //        mActivity.finish();
        if (mActivity == null) {
            mRoomActivity.finishPlayer();
        } else {
            mActivity.finishPlayer();
        }

    }

    /**
     * 锁屏
     *
     * @param isLock
     */
    public void setLock(boolean isLock) {
        if (mOrientationSensorListener != null) {
            mOrientationSensorListener.setLock(isLock);
        }
    }

    /**
     * 锁屏一次
     *
     * @param orientation
     */
    public void lockOnce(int orientation) {
        if (mOrientationSensorListener != null) {
            mOrientationSensorListener.lockOnce(orientation);
        }
    }

    /**
     * 是否锁屏
     *
     * @return
     */
    public boolean isLock() {
        if (mOrientationSensorListener != null) {
            return mOrientationSensorListener.isLock();
        }

        return false;
    }

    private void refreshLandspaceWhenLock() {
        if (mOrientationSensorListener != null) {
            mOrientationSensorListener.refreshLandspaceWhenLock();
        }
    }

    public void onDestory() {
        if (mSensorManager != null) {
            if (mOrientationSensorListener != null) {
                mSensorManager.unregisterListener(mOrientationSensorListener);
                mOrientationSensorListener = null;
            }

            if (mPanoramaSensorListener != null) {
                mSensorManager.unregisterListener(mPanoramaSensorListener);
            }
            if (mPanoramaSensorListenerG != null) {
                mSensorManager.unregisterListener(mPanoramaSensorListenerG);
            }
        }
    }

    public void onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return;
        }
        if (mActivity == null) {
            if (mRoomActivity.getGestureController() != null) {
                int volNum = mRoomActivity.getGestureController().getCurSoundVolume();
                boolean isUp = false;
                if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
                    volNum += 1;
                    isUp = true;
                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    volNum -= 1;
                    isUp = false;
                }
                // 发送通知
                mRoomActivity.getGestureObservable()
                             .notifyObservers(new AlbumGestureObservable.VolumeChangeNotify(mRoomActivity
                                     .getGestureController()
                                     .getMaxSoundVolume(), volNum,
                                     isUp ? VolumnChangeStyle.UP : VolumnChangeStyle.DOWN));
                if (mRoomActivity.getPlayAdListener() != null &&
                        mRoomActivity.getPlayAdListener().getAdFragment() != null) {
                    mRoomActivity.getPlayAdListener().getAdFragment().setMuteViewStatus(volNum);
                }
            }
        } else {
            if (mActivity.getGestureController() != null) {
                int volNum = mActivity.getGestureController().getCurSoundVolume();
                boolean isUp = false;
                if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
                    volNum += 1;
                    isUp = true;
                } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
                    volNum -= 1;
                    isUp = false;
                }
                // 发送通知
                mActivity.getGestureObservable()
                         .notifyObservers(new AlbumGestureObservable.VolumeChangeNotify(mActivity.getGestureController()
                                                                                                 .getMaxSoundVolume(), volNum,
                                 isUp ? VolumnChangeStyle.UP : VolumnChangeStyle.DOWN));
                if (mActivity.getPlayAdListener() != null &&
                        mActivity.getPlayAdListener().getAdFragment() != null) {
                    mActivity.getPlayAdListener().getAdFragment().setMuteViewStatus(volNum);
                }
            }
        }

    }

    public void onResume() {
        if (mActivity == null) {
            if (mRoomActivity.getFlow() != null &&
                    mRoomActivity.getFlow().getPlayingVideo() != null &&
                    mRoomActivity.getFlow().getPlayingVideo().needPay() &&
                    mRoomActivity.getVipTrailListener() != null) {
                // 付费视频试看
                if (PreferencesManager.getInstance(mRoomActivity).isLogin()) {
                    if (!PreferencesManager.getInstance(mRoomActivity).isVip()) {
                        // 登录成功非会员
                        mRoomActivity.getVipTrailListener().setStateForStartByHasLogined(true);
                        mRoomActivity.getVipTrailListener().checkVipTrailIsStateEnd();
                    } else {
                        // 会员登录成功
                        mRoomActivity.getVipTrailListener().finish();
                        mRoomActivity.getFlow().retryPlay(true, false);
                    }
                }
            }
        } else {
            if (mActivity.getFlow() != null && mActivity.getFlow().getPlayingVideo() != null &&
                    mActivity.getFlow().getPlayingVideo().needPay() &&
                    mActivity.getVipTrailListener() != null) {
                // 付费视频试看
                if (PreferencesManager.getInstance(mActivity).isLogin()) {
                    if (!PreferencesManager.getInstance(mActivity).isVip()) {
                        // 登录成功非会员
                        mActivity.getVipTrailListener().setStateForStartByHasLogined(true);
                        mActivity.getVipTrailListener().checkVipTrailIsStateEnd();
                    } else {
                        // 会员登录成功
                        mActivity.getVipTrailListener().finish();
                        mActivity.getFlow().retryPlay(true, false);
                    }
                }
            }
        }

    }
}
